<?php
namespace Home\Controller;
use Think\Controller;
class orderBollGroundController extends Controller {
	public $bollgroundlist;
	public $useTime;
	public $useDate;
	
	function __construct($list,$time){
		$this->bollgroundlist = $list;
		$this->useTime = $time['time'];
		$this->useDate = $time['date'];
	}
	
	function getGround(){
		//根据选中的日期,进行球场初始化
	    foreach($this->bollgroundlist as $v){
		    $this->getFreeGround($v['bollgroundid']);
	    }
    }
    
	 function getFreeGround($bollgroundid){
	    $model = D('orderbolllist');
	    
	    //球场空闲时间
        $ballGroundExcessTime = $model->getExcessTime($bollgroundid,$this->useDate); 
		//判断用户选择时间是否在空闲时间之内
		foreach($ballGroundExcessTime as $k=>$v){
			$time = explode(":",$v);
			if($this->useTime[0] >= $time[0] && $this->useTime[1] <= $time[1]){
				echo "用户所选的时间从".$this->useTime[0].'到'.$this->useTime[1].'在球场ID为'.$bollgroundid.'的球场恰好有空闲,该空闲时间为'. $time[0]."到". $time[1].'<br/>';
				
			}	
		}
		
    }
	function initBollGround($openTime = null){
		$openTime = ($openTime == null)?json_encode(array("0:1440")):json_encode(array($openTime));
	 
		//从数据库中新建一条记录
		foreach($this->bollgroundlist as $v){
			$res = M('orderbolllist')->where('bollgroundid = %d && date="%s"',$v['bollgroundid'],$this->useDate)->find();
			if(!$res){
				$data['excesstime'] = $openTime;
				$data['date'] = $this->useDate;
				$data['bollgroundid'] = $v['bollgroundid'];
				M('orderbolllist')->add($data);
			}	
		}
	}
  
   

	//test 这里演示如何将用户选择填入数据库
	function setBollGround($bollgroundid,$date,$start,$end){
		
		//假设用户选择 A(ID=1)球场 ,时间为 330,800
		/*
			将用户的选择填入 540 800 1000 1320
			生成新的数据
			$data['excesstime'] = json_encode(array("0:330","1000:2400"));
			1100 1300
		*/

		//取原值
		$order = M('orderbolllist')->where('bollgroundid=%d && date="%s"',$bollgroundid,$date)->find();
	 	$excesstime= json_decode($order['excesstime']);
		//取用户选的值
		
		//合并
		foreach ($excesstime as $k => $v) {
			$time_array = explode(":",$v);
			foreach ($time_array as $ko => $vo) {
				 $time[] =(int) $vo;
			}	
		}	
		
		array_push($time,$start,$end);
		asort($time);

		$res = array_chunk($time,2);
		foreach ($res as $key => &$value) {
			$value = join($value,":");
		}

		$data['excesstime'] = json_encode($res);
 
	 	$bool = M('orderbolllist')->where('bollgroundid=%d && date="%s"',$bollgroundid,$date)->save($data);

	 	if ($bool) {
	 		echo "ok";
	 	}
	}

}